import { Web3 } from 'web3';
import {hideLoader, showLoader} from "./main.ts";
const options = {
    method: 'GET',
    headers: {
        accept: 'application/json',
        'x-api-key': import.meta.env.VITE_OPENSEA_KEY
    },
};
declare global {
    interface WindowEventMap {
        "eip6963:announceProvider": CustomEvent
    }
}

// Connect to the selected provider using eth_requestAccounts.
const connectWithProvider = async (wallet: EIP6963AnnounceProviderEvent["detail"]) => {
    try {
        const web3 = new Web3(wallet.provider)
        await wallet.provider
            .request({ method: "eth_requestAccounts" })

        document.querySelector<HTMLDivElement>("#providerButtons").style.display = 'none'

        const accounts = await web3.eth.getAccounts();

        showLoader();

        const response = await fetch(`https://testnets-api.opensea.io/api/v2/chain/sepolia/account/${accounts[0]}/nfts`, options)
        const data = await response.json();

        hideLoader();

        const gridTable = document.querySelector<HTMLDivElement>('#grid');
        data.nfts.forEach(nft => {
            gridTable.insertAdjacentHTML('beforeend', `
                <div>
                    <img src="${nft.image_url}" alt="${nft.name}" />
                    <div>${nft.name}</div>
                    <div>${nft.contract}</div>
                </div>
            `)
        })

        const getNFTButton = document.querySelector<HTMLDivElement>('#get-user-nft');
        getNFTButton.style.display = 'inherit';
    } catch (error) {
        console.error("Failed to connect to provider:", error)
    }
}

// Display detected providers as connect buttons.
export function listProviders(element: HTMLDivElement) {
    window.addEventListener("eip6963:announceProvider",
        (event: EIP6963AnnounceProviderEvent) => {
            const button = document.createElement("button")

            button.innerHTML = `
        <img src="${event.detail.info.icon}" alt="${event.detail.info.name}" />
        <div>${event.detail.info.name}</div>
      `
            // Call connectWithProvider when a user selects the button.
            button.onclick = () => connectWithProvider(event.detail)
            element.appendChild(button)
        }
    )

    // Notify event listeners and other parts of the dapp that a provider is requested.
    window.dispatchEvent(new Event("eip6963:requestProvider"))
}